// Package middleware
// @File: i18n.go
// @Description: 国际化中间价
// @Author: YaoRuiQi
// @Date: 2025/8/23 02:50

package middleware

import (
	"GinStandardTemplate/internal/pkg/codes"
	"GinStandardTemplate/internal/pkg/contextUtils"
	"GinStandardTemplate/internal/pkg/response"
	"GinStandardTemplate/utils/i18n"
	"GinStandardTemplate/utils/logger"

	"github.com/gin-gonic/gin"
	"golang.org/x/text/language"
)

// I18nMiddleware
//
//	@Description: 国际化处理
//	@return gin.HandlerFunc
func I18nMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取语言，初始化i18n
		accept := c.GetHeader("Accept-Language")
		tags, _, err := language.ParseAcceptLanguage(accept)
		if err != nil || len(tags) == 0 {
			tags = []language.Tag{language.Chinese}
		}
		matchedTag, _, _ := i18n.LanguageMatcher.Match(tags...)
		localizer := i18n.NewI18nLocalizer(matchedTag.String())

		// 如果没有获取到ctx，则推出错误
		ctx, getRequestContentErr := contextUtils.FromContext(c.Request.Context())
		if getRequestContentErr != nil {
			logger.Logger.Error("国际化中间价context未找到RequestContext")
			response.JSONResponse(
				c,
				codes.InternalError.Code(),
				i18n.GetMessage(
					&contextUtils.RequestContext{Logger: logger.Logger, Localizer: localizer},
					codes.InternalError.MessageID(),
					nil,
				),
				nil,
			)
			c.Abort()
			return
		}

		// 更新请求上下文，增加国际化
		c.Request = c.Request.WithContext(contextUtils.NewRequestContext(
			c.Request.Context(), &contextUtils.RequestContext{
				RequestID: ctx.RequestID,
				Localizer: localizer,
			},
		))

		c.Next()
	}
}
